package com.alibaba.nacos.config.server.jpa.config;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;

import com.alibaba.nacos.config.server.service.DataSourceService;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-12
 */
@Service("basicDataSourceService")
@Primary
public class JpaDataSourceService implements DataSourceService {

    /**
     * JDBC执行超时时间, 单位秒
     */
    private int queryTimeout = 3;

    private static final int TRANSACTION_QUERY_TIMEOUT = 5;

    private JdbcTemplate jt;
    private DataSourceTransactionManager tm;
    private TransactionTemplate tjt;

    @Value("${spring.datasource.druid.url}")
    private String url;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() {

        queryTimeout = NumberUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
        jt = new JdbcTemplate();
        /**
         *  设置最大记录数，防止内存膨胀
         */
        jt.setMaxRows(50000);
        jt.setQueryTimeout(queryTimeout);
        jt.setDataSource(dataSource);

        tm = new DataSourceTransactionManager();
        tjt = new TransactionTemplate(tm);
        /**
         *  事务的超时时间需要与普通操作区分开
         */
        tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
        if (!STANDALONE_MODE || PropertyUtil.isStandaloneUseMysql()) {
            reload();
        }
    }

    @Override
    public synchronized void reload() {

    }

    @Override
    public boolean checkMasterWritable() {
       return true;
    }

    @Override
    public JdbcTemplate getJdbcTemplate() {
        return this.jt;
    }

    @Override
    public TransactionTemplate getTransactionTemplate() {
        return this.tjt;
    }

    @Override
    public String getCurrentDBUrl() {
        return url;
    }

    @Override
    public String getHealth() {
        return "UP";
    }

}
